import React, { useEffect, useState,useRef } from "react";
import { uuid } from "../util";
import styles from "./index.less";
import useDropInfo from "./useDropInfo";
import { ImageList, Goods,  Box } from "./components";
const componentList = { ImageList, Goods, Box };
import {useSortable, useDrag, useIframeDrop,DragView, DropView } from 'react-iframe-drag'

function Dnd() {
  const [list, setList] = useState([]);
   const nodesId = useRef()
  const  getItem=(id)=>{
   for(let i=0;i<list.length;i++){
      let item=list[i]
     if(id==item?.id){
        return item
      }
    }
    return null
  }
  useSortable(nodesId, {
    onChange: (ids) => {
      console.log("useSortable", ids);
      const _list=ids.map((item)=>{
        const _item=getItem(item)
        if(_item){
          return _item
        }
      })
     setList([..._list])
    },
    onClick:({index,id})=>{
       window.parent.postMessage({ index,id, type: 6,list}, "*");  
    }
  },[list]);
  useDropInfo(
    "nodesId",
    (data) => {
      window.top.postMessage({ ...data, type: 2 }, "*");
    },
    [list]
  );
  const onMessage = (e) => {
    const { type, list } = e.data;
    if (type === 0) setList([...list]);
  };
  useEffect(() => {
    window.addEventListener("message", onMessage);
    return () => {
      window.removeEventListener("message", onMessage);
    };
  }, []);
  useEffect(() => {
     window.parent.postMessage({ list, type: 5 }, "*"); 
  },[list])
  return (
    <div id="nodesId" ref={nodesId} className={styles.container}>
      {list.map((item,index) => {
        const View = componentList[item.name];
        return (
          <DragView  index={index} item={item} key={item?.cid}>
            <View  template={item?.template}/>
          </DragView>
        );
      })}
    </div>
  );
}
export default Dnd;
